package com.xudow.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.ui.task.RegisterTask;
import com.xudow.app.ui.task.VcodeTask;
import com.xudow.app.util.Maps;
import com.xudow.app.util.StringUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 注册Activity
 *
 * @author lukecheng
 */
public class RegisterActivity extends BaseActivity {

    private LinearLayout vcodeSendBtn;
    private TextView vcodeText;

    private EditText cellphoneEditText;
    private EditText passwordEditText;
    private EditText vcodeEditText;

    private Button loginBtn;

    private RadioButton studentRadioBtn, familyRadioBtn;

    /**
     * 验证码重新获取倒计时
     */
    private VcodeTask vcodeTask;
    private int vcodeCountDown = 60;
    private Timer vcodeTimer;
    private TimerTask vcodeTimerTask;

    private RegisterTask registerTask;

    private void initVcodeTimerTask() {
        vcodeTimerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (vcodeCountDown <= 0) {
                            vcodeSendBtn.setClickable(true);
                            vcodeText.setText(getString(R.string.common_vcode_again));
                            vcodeTimerTask.cancel();
                        } else {
                            String countdownTxt = getString(R.string.common_vcode_countdown, vcodeCountDown);
                            vcodeText.setText(countdownTxt);
                        }

                        vcodeCountDown--;
                    }
                });
            }
        };
    }

    /**
     * 获取验证码Handler
     */
    private Handler vcodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            if (VcodeTask.SUCCESS == msg.what) {
                String vcodeSuccess = getString(R.string.common_vcode_success);
                Toast.makeText(RegisterActivity.this, vcodeSuccess, Toast.LENGTH_SHORT).show();

                vcodeSendBtn.setClickable(false);

                initVcodeTimerTask();
                vcodeTimer = new Timer();
                vcodeTimer.scheduleAtFixedRate(vcodeTimerTask, 1000, 1000);
            } else {
                String errVcode = getString(R.string.common_vcode_err);
                Toast.makeText(RegisterActivity.this, errVcode, Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        passwordEditText = (EditText) findViewById(R.id.password);
        cellphoneEditText = (EditText) findViewById(R.id.cellphone);
        vcodeEditText = (EditText) findViewById(R.id.vcode);

        studentRadioBtn = (RadioButton) findViewById(R.id.student_radio_btn);
        familyRadioBtn = (RadioButton) findViewById(R.id.family_radio_btn);

        vcodeSendBtn = (LinearLayout) findViewById(R.id.vcode_send_btn);
        vcodeText = (TextView) findViewById(R.id.vcode_btn_txt);

        loginBtn = (Button) findViewById(R.id.login_btn);
    }

    /**
     * 返回点击事件
     *
     * @param view
     */
    public void onBackBtnClick(View view) {
        finish();
    }

    /**
     * 身份选择
     *
     * @param view
     */
    public void onFamilyIdentifyClick(View view) {
        studentRadioBtn.setChecked(false);
        familyRadioBtn.setChecked(false);

        ((RadioButton) view).setChecked(true);
    }

    /**
     * 获取验证码
     *
     * @param view
     */
    public void onGetVcodeClick(View view) {
        String cellphone = cellphoneEditText.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_format_err));
            return;
        }

        showLodingDialog(getString(R.string.common_vocde_send));

        HashMap<String, String> vcodeParams = Maps.newHashMap();
        vcodeParams.put("phone", cellphone);
        vcodeParams.put("type", Config.VOCDE_TYPE_REGISTER);
        vcodeParams.put("login", "true");

        vcodeTask = new VcodeTask(this, vcodeHandler);
        vcodeTask.execute(vcodeParams);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (null != vcodeTask && !vcodeTask.isCancelled()) {
                vcodeTask.cancel(true);
                vcodeTask = null;
            }

            if (null != registerTask && !registerTask.isCancelled()) {
                registerTask.cancel(true);
                registerTask = null;
            }

            loginBtn.setEnabled(true);
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * 注册按钮点击事件
     *
     * @param view
     */
    public void onRegBtnClick(View view) {
        String cellphone = cellphoneEditText.getText().toString().trim();
        if (StringUtils.isEmpty(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_required));
            return;
        }

        if (!StringUtils.isMobile(cellphone)) {
            cellphoneEditText.setError(getString(R.string.cellphone_format_err));
            return;
        }

        String password = passwordEditText.getText().toString().trim();
        if (StringUtils.isEmpty(password)) {
            passwordEditText.setError(getString(R.string.password_required));
            return;
        }

        String vcode = vcodeEditText.getText().toString().trim();
        if (StringUtils.isEmpty(vcode)) {
            vcodeEditText.setError(getString(R.string.vcode_required));
            return;
        }

        String role = Config.USER_ROLE_PARENT;
        /*if (studentRadioBtn.isChecked()) {
            role = Config.USER_ROLE_STUDENT;
        }*/
        if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isStudent",false)){
            role = Config.USER_ROLE_STUDENT;
        }
        HashMap<String, String> params = Maps.newHashMap();
        params.put("phone", cellphone);
        params.put("role", role);
        params.put("password", password);
        params.put("vcode", vcode);

        showLodingDialog(getString(R.string.registering));

        registerTask = new RegisterTask(this, registerHandler);
        registerTask.execute(params);
    }

    /**
     * 登陆Handler
     */
    private Handler registerHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();

            loginBtn.setEnabled(true);

            switch (msg.what) {
                case RegisterTask.SUCCESS:
                    loginSuccess();
                    break;
                case RegisterTask.ERROR:
                case RegisterTask.ERROR_WITH_MESSAGE:
                    loginError(msg.getData());
                    break;
            }
        }
    };

    private void loginSuccess() {
        String successStr = getString(R.string.register_success);
        Toast.makeText(this, successStr, Toast.LENGTH_LONG).show();
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    private void loginError(Bundle data) {
        if (null != data && null != data.getString("errMessage")) {
            String msg = data.getString("errMessage");
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        } else {
            String msg = getString(R.string.register_fail);
            Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
        }
    }
}
